import PropTypes from "prop-types";
import React, { memo, useEffect, useState } from "react";
import { Pagination } from "antd";
import { PaginationWrapper } from "./style";
import { shallowEqual, useSelector, useDispatch } from "react-redux";
import {
  changeCurrentPageAction,
  changeIsLoadingAction,
  changeRoomListAction,
} from "@/store/modules/entire";
import { getEntireRoomList } from "@/services";

const EntirePagination = memo((props) => {
  const { roomList, currentPage, totalCount } = useSelector(
    (state) => ({
      roomList: state.entire.roomList,
      currentPage: state.entire.currentPage,
      totalCount: state.entire.totalCount,
    }),
    shallowEqual
  );

  const [page, setPage] = useState(currentPage);
  const dispatch = useDispatch();
  useEffect(() => {
    getAll();
  }, [dispatch, page]);

  function pageChangeHandle(page, pageSize) {
    window.scrollTo(0, 0);
    setPage(page - 1);
    console.log(page, pageSize);
  }

  async function getRoomList() {
    dispatch(changeIsLoadingAction(true));
    const res = await getEntireRoomList(page);
    dispatch(changeRoomListAction(res));
    dispatch(changeCurrentPageAction(page));
    dispatch(changeIsLoadingAction(false));
  }

  async function getAll() {
    try {
      await Promise.all([getRoomList()]);
    } catch (error) {
      console.log(error, "error");
    }
  }
  return (
    <PaginationWrapper>
      {!!roomList.length && (
        <Pagination
          total={totalCount}
          onChange={pageChangeHandle}
          defaultPageSize={20}
          showTotal={(totalCount) => `共${totalCount} 个房源`}
        />
      )}
    </PaginationWrapper>
  );
});

EntirePagination.propTypes = {};

export default EntirePagination;
